package com.shaoshaohuo.app;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.mobileim.YWAPI;
import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.alibaba.sdk.android.media.MediaService;
import com.alibaba.wxlib.util.SysUtil;
import com.google.gson.Gson;
import com.iflytek.cloud.SpeechUtility;
import com.liam.imageload.LoadUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.shaoshaohuo.app.constant.DbVersions;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.AddedService;
import com.shaoshaohuo.app.entity.AddedServiceEntity;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CarTypeEntity;
import com.shaoshaohuo.app.entity.CarTypeFirst;
import com.shaoshaohuo.app.entity.EcCategoryEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper.Field;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.Location2Util;
import com.shaoshaohuo.app.utils.city.json.Root;
import com.shaoshaohuo.app.utils.city.json.list;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.umeng.analytics.MobclickAgent;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 测试提交sadasda  aaaa
 *aaaaaa
 * @author: yusonglin
 */
public class SshApplication extends MultiDexApplication {

    // 控制是否返回选择角色页面
    public static boolean isComeBackSelectRoleTypeActivity = false;
    // 当前显示首页 是电商 或者 物流 1为物流 2 为电商
    public static int main_state = 0;
    private static Context mContext;
    private static SshApplication application;
    private JPushCallBack callBack;

    private SetAliasHandler handler;

    public static SshApplication getSharedInstance() {
        return application;
    }

    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        mContext = this;

        initXUtils();
        LoadUtils.init(getContext());
//                startLocationService(); //初始化放到WelcomeActivity初始化，解决android6.0动态权限问题
        initUMeng();
        initPush();
        initUniversal();
        initXunfei();

                /*initCity();
                initCarType();
                initEcCategory();
                initAddedService();*/

        initIM();
//		collectionUserDeviceInfo();
    }


    private void initXUtils() {
        x.Ext.init(this);
        x.Ext.setDebug(false);
//		DbHelper.makeDbHelper(mContext);
//		registerDbEntity();
//		DbHelper.getInstance().judgeUpgrade();
    }

    private void initUMeng() {
//		AnalyticsConfig.setAppkey(this, AppConfig.UMENG_APP_KEY);
        MobclickAgent.enableEncrypt(true);
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setDebugMode(false);
    }

    /**
     * 采集用户设备信息
     */
    private void collectionUserDeviceInfo() {
        RequestService.getInstance().appStart(getContext(), BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                LogUtil.i(SshApplication.class.getSimpleName(), "采集用户设备信息 OK");
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                LogUtil.i(SshApplication.class.getSimpleName(), "采集用户设备信息 ERROR");
            }

        });
    }

    /**
     * 初始化IM即时通讯
     */
    public void initIM() {
        // 必须首先执行这部分代码, 如果在":TCMSSevice"进程中，无需进行云旺（OpenIM）和app业务的初始化，以节省内存;
//        SysUtil.setApplication(this);
//        if (SysUtil.isTCMSServiceProcess(this)) {
//            return;
//        }
//        // 初始化阿里百川IM


//todo Application.onCreate中，首先执行这部分代码，以下代码固定在此处，不要改动，这里return是为了退出Application.onCreate！！！
        if (mustRunFirstInsideApplicationOnCreate()) {
            //todo 如果在":TCMSSevice"进程中，无需进行openIM和app业务的初始化，以节省内存
            return;
        }
        YWAPI.init(this, "23275592");
//        IMFactory.init("");
        //初始化云旺SDK
        //初始化反馈功能(未使用反馈功能的用户无需调用该初始化)
        //初始化多媒体SDK，小视频和阅后即焚功能需要使用多媒体SDK
        AlibabaSDK.asyncInit(this, new InitResultCallback() {
            @Override
            public void onSuccess() {
                Log.e("TAG", "-----initTaeSDK----onSuccess()-------");
                MediaService mediaService = AlibabaSDK.getService(MediaService.class);
                mediaService.enableHttpDNS(); //果用户为了避免域名劫持，可以启用HttpDNS
                mediaService.enableLog(); //在调试时，可以打印日志。正式上线前可以关闭
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("TAG", "-------onFailure----msg:" + msg + "  code:" + code);
            }
        });

    }

    private void initXunfei() {
        SpeechUtility.createUtility(this, "appid=55c9bdc3");
    }

    private void initUniversal() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
        // ImageLoader.getInstance().init(
        // new ImageLoaderConfiguration.Builder(this).build());
    }

    private void initPush() {
        JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this); // 初始化 JPush
//        if (AccountManager.isLogin()) {
            initAliasAndTags();
//        }
    }

    private void initAliasAndTags() {
        String mobile = AccountManager.getUserInfo().getMobile();
        if(TextUtils.isEmpty(mobile)){
            mobile="16666666666";
        }
        String alias = SharedPreferencesHelper.getString(Field.PUSH_DEVICE_ALIAS, "");
        if (!alias.equals(mobile)) {
            Log.e("TAG", "initAliasAndTags: 极光初始化" );
            Set<String> tags = new HashSet<>();
            tags.add("android");
            callBack = new JPushCallBack();
            handler = new SetAliasHandler(this, mobile, tags);
            handler.sendEmptyMessage(0);
        }
    }

    private void startLocationService() {
//		Intent intent = new Intent(this, LocationService.class);
//		startService(intent);
//		LocationUtil.reportGeo(this);
        Location2Util.getInstance(this).startLocation();
    }


    private void initCity() {
        int oldVersion = SharedPreferencesHelper.getInt(SharedPreferencesHelper.Field.AREA_DB_VERSION, -1);
        if (oldVersion < DbVersions.AREA_VERSION) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream input = getResources().openRawResource(R.raw.city);
                    BufferedReader br = new BufferedReader(new InputStreamReader(input));
                    Root inEntity = new Gson().fromJson(br, Root.class);
                    List<list> proList = inEntity.getData().getList();
                    ArrayList<Area> areaList = new ArrayList<Area>();

                    for (list li : proList) {
//                        Area area = new Area();
//                        area.setAreaId(li.getId());
//                        area.setLat(li.getLat());
//                        area.setLevelType(li.getLeveltype());
//                        area.setLng(li.getLng());
//                        area.setName(li.getProname());
//                        areaList.add(area);
//                        if (li.getCitys() != null) {
//                            for (citys ci : li.getCitys()) {
//                                area = new Area();
//                                area.setAreaId(ci.getId());
//                                area.setLat(ci.getLat());
//                                area.setLevelType(ci.getLeveltype());
//                                area.setLng(ci.getLng());
//                                area.setName(ci.getCityname());
//                                area.setParentAreaId(ci.getPid());
//                                areaList.add(area);
//                                if (ci.getAreas() != null) {
//                                    for (areas ar : ci.getAreas()) {
//                                        area = new Area();
//                                        area.setAreaId(ar.getId());
//                                        area.setLat(ar.getLat());
//                                        area.setLevelType(ar.getLeveltype());
//                                        area.setLng(ar.getLng());
//                                        area.setName(ar.getCityname());
//                                        area.setParentAreaId(ar.getPid());
//                                        areaList.add(area);
//                                    }
//                                }
//                            }
//                        }
                    }
                    DaoUtils.reloadAllAreas(areaList);
                }
            }).start();

            SharedPreferencesHelper.setInt(SharedPreferencesHelper.Field.AREA_DB_VERSION, DbVersions.AREA_VERSION);
        }

    }

    private void initCarType() {
        List<CarTypeFirst> findAllProvince = DaoUtils.findAllCartype();

        if (findAllProvince != null && !findAllProvince.isEmpty() && DaoUtils.findAllCartype("1") != null) {
            // ToastUtil.toast("findAllProvince:" + findAllProvince.size());
            return;
        }
        RequestService.getInstance().getCarType(this, CarTypeEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    CarTypeEntity entity = (CarTypeEntity) resultData;
                    DaoUtils.saveCartype(entity);
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
            }
        });
    }

    private void initEcCategory() {
        //版本更新，后要更新内容
        if (DeviceHelper.getVersionCode(this) > SharedPreferencesHelper.getInt(Field.EC_CATEGORY_VERSION, -1)) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    InputStream input = getResources().openRawResource(R.raw.ec_category);
                    BufferedReader br = new BufferedReader(new InputStreamReader(input));
                    EcCategoryEntity entity = new Gson().fromJson(br, EcCategoryEntity.class);
                    DaoUtils.saveEcCategory(entity);
                    SharedPreferencesHelper.setInt(Field.EC_CATEGORY_VERSION, DeviceHelper.getVersionCode(SshApplication.this));
                }

            }).start();
            return;
        }

    }

    private void initAddedService() {
        List<AddedService> findAllProvince = DaoUtils.findAllAddedService();
        if (findAllProvince != null && !findAllProvince.isEmpty()) {
            // ToastUtil.toast("findAllProvince:" + findAllProvince.size());
            return;
        }
        RequestService.getInstance().getAddedService(this, AddedServiceEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    AddedServiceEntity entity = (AddedServiceEntity) resultData;
                    DaoUtils.saveAddedService(entity);
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
            }
        });
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Location2Util.getInstance(this).destroy();
    }

    /**
     * 设置 tags handler
     *
     * @author cao
     */
    public class SetAliasHandler extends Handler {
        private Context context;
        private String mobile;
        private Set<String> tags;

        public SetAliasHandler(Context context, String mobile, Set<String> tags) {
            this.context = context;
            this.mobile = mobile;
            this.tags = tags;
        }

        @Override
        public void handleMessage(Message msg) {
            JPushInterface.setAliasAndTags(context, mobile, tags, callBack);
        }
    }

    /**
     * jpush 设置回调
     *
     * @author cao
     */
    private class JPushCallBack implements TagAliasCallback {
        @Override
        public void gotResult(int arg0, String arg1, Set<String> arg2) {
            Log.e("TAG", "gotResult:====================== " + arg0);
            switch (arg0) {
                case 0:
                    handler = null;
                    callBack = null;
                    SharedPreferencesHelper.setString(Field.PUSH_DEVICE_ALIAS, arg1);
                    break;
                case 6002:
                    handler.sendEmptyMessageDelayed(0, 1000 * 60);
                    break;
            }

        }

    }

    private boolean mustRunFirstInsideApplicationOnCreate() {
        //必须的初始化
        SysUtil.setApplication(this);
        return SysUtil.isTCMSServiceProcess(getApplicationContext());
    }
}
